package com.example.android.plugin.framework;

import java.util.ArrayList;
import java.util.List;

import com.example.android.plugin.framework.beans.Plugin;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

/**
 * 查找插件
 */
public class PluginSearch {

	/**
	 * 查找插件
	 */
	public PluginSearch() {
	}

	/**
	 * 获取所有插件
	 * 
	 * @param context
	 *            句柄
	 * @return
	 * @throws NameNotFoundException
	 */
	public List<Plugin> getPlugins(Context context)
			throws NameNotFoundException {

		List<Plugin> plugins = new ArrayList<Plugin>();

		// 获取自身的suid
		PackageManager pkgManager = context.getPackageManager();
		String pkgName = context.getPackageName();
		String sharedUID = pkgManager.getPackageInfo(pkgName,
				PackageManager.GET_UNINSTALLED_PACKAGES).sharedUserId;

		List<PackageInfo> pkgs = pkgManager
				.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
		for (PackageInfo pkg : pkgs) {
			// 查找具有相同suid的包，并且排除自身
			if (!sharedUID.equals(pkg.sharedUserId)
					|| pkgName.equals(pkg.packageName))
				continue;

			Plugin plugin = new Plugin();
			plugin.setPkgInfo(pkg);
			plugin.setPluginLable(pkgManager.getApplicationLabel(
					pkg.applicationInfo).toString());
			plugins.add(plugin);

		}

		return plugins;
	}
}
